const express = require('express')
const sqlQuery = require('./mysql');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const { read } = require('fs');
const { json } = require('express');
const bodyParser = require('body-parser');
const querystring = require('querystring');

//文件上传
const multer = require('multer')
const fs = require("fs")

const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

const secret = 'aries'
//生成token
function createToken(info) {
  let token = jwt.sign(info, secret, {
    //Token有效时间 单位s 10个小时
    expiresIn: 60 * 60 * 10
  })
  return token
}
//验证token
function verifyToken(token) {
  return new Promise((resolve, reject) => {
    jwt.verify(token, secret, (error, result) => {
      if (error) {
        reject(error)
      } else {
        resolve(result)
      }
    })
  })
}


function md5(str) {
  let salt = 'aries'
  let hash = crypto.createHash('md5')
  str = salt + str
  hash.update(str)
  return hash.digest('hex')
}

//运行跨域
// app.all('*', function (req, res, next) {
//   res.header("Access-Control-Allow-Origin", "*");
//   res.header("Access-Control-Allow-Headers", "X-Requested-With");
//   res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
//   res.header("X-Powered-By", ' 3.2.1');
//   //返回数据格式为json字符串
//   // res.header("Content-Type", "application/json;charset=utf-8");
//   //返回数据格式设置为html文档
//   res.header("Content-Type", "text/html;charset=utf-8");
//   next();

// });
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  res.header("X-Powered-By", ' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});


//管理员登录信息
app.get('/mlogin', async (req, res) => {
  let { username, password } = req.query;
  password = md5(password)
  let strSql = "select * from employee where emp_user = ? and emp_pwd = ?";
  let arr = [username, password]
  let result = await sqlQuery(strSql, arr)
  if (result.length != 0) {
    let strSql = "update employee set isLogin=? where emp_user = ?";
    let changestatus = await sqlQuery(strSql, [1, username])
    let InFo = { id: result[0].emp_id, usename: result[0].emp_user }
    let token = result[0].emp_role
    // console.log(token);
    res.json({
      status: 1,
      token: token,
      InFo: InFo
    })
  } else {
    res.json({
      status: 0,
    })
  }
})





//管理员页面电影信息展示
app.get('/message/play', async (req, res) => {
  let { query, pagenum } = req.query
  // console.log(query,pagenum);
  if (query == '') {
    let strSql = "select COUNT(*) as total from movie"
    let totalpage = await sqlQuery(strSql)
    strSql = "select * from movie limit ?,5"
    let movies = await sqlQuery(strSql, [(pagenum - 1) * 5])
    res.json({
      totalpage, movies
    })
  } else {
    let strSql = "select COUNT(*) as total from movie where title like '%" + query + "%'"
    let totalpage = await sqlQuery(strSql)
    strSql = "select * from movie where title like '%" + query + "%' limit ?,5"
    let movies = await sqlQuery(strSql, [(pagenum - 1) * 5])
    res.json({
      totalpage, movies
    })
  }

})

//添加电影
app.post('/message/addmovie', async (req, res) => {
  // console.log(req.body);
  let { title, direct, actor, type, area, language, date, filmlen, introduction, score, cover } = req.body.data
  let strSql = "select * from movie where title = ?"
  let constt = await sqlQuery(strSql, [title])
  // console.log(constt);
  if (constt.length != 0) {
    res.json(0)
  } else {
    let strSql = "insert into movie (title,direct,actor,type,area,language,date,filmlen,introduction,score,cover) values (?,?,?,?,?,?,?,?,?,?,?)"
    let result = await sqlQuery(strSql, [title, direct, actor, type, area, language, date, filmlen, introduction, score, cover])
    // console.log(result);
    res.json(1)
  }
})


//查询电影信息
app.get("/movie/:id", async (req, res) => {
  // console.log(req.params.id);
  let strSql = "select * from movie where id = ?"
  let result = await sqlQuery(strSql, [req.params.id])
  // console.log(result);
  // let { title, direct, actor, type, area, language, date, filmlen, introduction, score } = result[0]
  res.json(result[0])
})

//更新电影信息
app.put('/movie/:id', async (req, res) => {
  // console.log(req.params.id);
  // console.log(req.body);
  let { direct, actor, type, area, language, date, filmlen, introduction, score } = req.body;
  let strSql = "UPDATE movie set direct = ?, actor = ?, type = ?, area = ?, language = ?, date = ?, filmlen = ?, introduction = ?, score = ? where id = ?"
  let result = await sqlQuery(strSql, [direct, actor, type, area, language, date, filmlen, introduction, score, req.params.id])
  res.json(1)
})

//删除电影信息
app.delete('/movie/:id', async (req, res) => {
  // console.log(req.params.id);
  let strSql = "delete from movie where id = ?"
  let result = await sqlQuery(strSql, [req.params.id])
  // console.log(result);
  // console.log(result.affectedRows);
  if (result.affectedRows == 1) {
    res.json(1)
    return
  }
  res.json(0)
})

//管理员页面影厅信息展示
app.get('/message/screens', async (req, res) => {
  let { query, pagenum } = req.query
  if (query == '') {
    let strSql = "select COUNT(*) as total from screen"
    let totalpage = await sqlQuery(strSql)
    strSql = "select * from screen limit ?,12"
    let screens = await sqlQuery(strSql, [(pagenum - 1) * 12])
    res.json({
      totalpage, screens
    })
  } else {
    let strSql = "select COUNT(*) as total from screen where name like '%" + query + "%'"
    let totalpage = await sqlQuery(strSql)
    strSql = "select * from screen where name like '%" + query + "%' limit ?,12"
    let screens = await sqlQuery(strSql, [(pagenum - 1) * 12])
    res.json({
      totalpage, screens
    })
  }
})

//新增影厅信息
app.post("/message/addscreen", async (req, res) => {
  // console.log(req.query);
  let { name, row, col, status, setList } = req.query
  let strSql = "select * from screen where name = ?"
  let constt = await sqlQuery(strSql, [name])
  if (constt.length != 0) {
    res.json(0)
  } else {
    //新增影厅信息
    let strSql = "insert into screen (name, row, col, status) values (?,?,?,?)"
    let result = await sqlQuery(strSql, [name, row, col, status])
    //新增座位表
    strSql = "select id from screen where name = ?"
    result = await sqlQuery(strSql, [name])
    let id = result[0].id
    // console.log(id);
    strSql = "insert into seat (studio_id,set_state) values (?,?)"
    result = await sqlQuery(strSql, [id, setList])
    res.json(1)
  }
})

//查询影厅信息根据ID   展示座位
app.get("/screen/:id", async (req, res) => {
  // console.log(req.params.id);
  let strSql = 'select * from screen where id = ?'
  let result = await sqlQuery(strSql, [req.params.id])
  strSql = "select set_state from seat where studio_id = ? ";
  let state = await sqlQuery(strSql, [req.params.id])
  let RC = "select row,col from screen where id = ?"
  // console.log(state[0].set_state);
  !state[0].set_state ? [] : state[0].set_state
  res.json({
    screen: result,
    seat: state[0].set_state,
  })
})

//更新座位信息
app.post("/seat/:id", async (req, res) => {
  let { warnseats, noneseats } = req.body
  // console.log(req.body);
  // console.log(req.params.id);
  let strSql = "select set_state as state from seat where studio_id = ?"
  let seat = await sqlQuery(strSql, [req.params.id])
  // console.log(seat[0].state);
  seat = JSON.parse(seat[0].state)
  for (let i = 0; i < warnseats.length; i++) {
    seat[warnseats[i][0]][warnseats[i][1]] = -1
  }
  for (let i = 0; i < noneseats.length; i++) {
    seat[noneseats[i][0]][noneseats[i][1]] = -2
  }
  // console.log(seat);
  seat = JSON.stringify(seat)

  strSql = "update seat set set_state = ? where studio_id = ?"
  let result = await sqlQuery(strSql, [seat, req.params.id])
  res.json(1)
})

//删除影厅信息
app.delete('/screen/:id', async (req, res) => {
  // 影厅表
  let strSql = "delete from screen where id = ?"
  let result = await sqlQuery(strSql, [req.params.id])
  // 座位表
  strSql = "delete from seat where studio_id = ?"
  result = await sqlQuery(strSql, [req.params.id])
  res.json(1)
})


//展示员工信息
app.get('/message/staff', async (req, res) => {
  let { query, pagenum } = req.query
  if (query == '') {
    let strSql = "select COUNT(*) as total from employee where isDelete = 0"
    let totalpage = await sqlQuery(strSql)
    strSql = "select * from employee where isDelete = 0 limit ?,5"
    let employees = await sqlQuery(strSql, [(pagenum - 1) * 5])
    // console.log(employees);
    res.json({
      totalpage, employees
    })
  } else {
    let strSql = "select COUNT(*) as total from employee where isDelete = 0 and emp_user like '%" + query + "%'"
    let totalpage = await sqlQuery(strSql)
    strSql = "select * from employee where isDelete = 0 and emp_user like '%" + query + "%' limit ?,5"
    let employees = await sqlQuery(strSql, [(pagenum - 1) * 5])
    res.json({
      totalpage, employees
    })
  }
})

//添加员工
app.post('/message/addstaff', async (req, res) => {
  // console.log(req.body);

  let { emp_user, emp_pwd, emp_role, emp_gender, emp_tel, emp_email, emp_status } = req.body
  emp_pwd = md5(emp_pwd)
  emp_gender = emp_gender == '1' ? '男' : '女'
  let strSql = "select * from employee where emp_user = ?"
  let constt = await sqlQuery(strSql, [emp_user])
  // console.log(constt);
  if (constt.length != 0) {
    res.json(0)
  } else {
    let strSql = "insert into employee (emp_user,emp_pwd,emp_role,emp_gender,emp_tel,emp_email,emp_status,isDelete) values (?,?,?,?,?,?,?,?)"
    let result = await sqlQuery(strSql, [emp_user, emp_pwd, emp_role, emp_gender, emp_tel, emp_email, emp_status, 0])
    res.json(1)
  }
})


//删除员工信息
app.delete("/staff/:id", async (req, res) => {
  // console.log(req.params.id);
  let strSql = "UPDATE employee set isDelete = 1 where emp_id = ?"
  let result = await sqlQuery(strSql, [req.params.id])
  res.json(1)
})

//修改员工信息
app.put("/staff/:id", async (req, res) => {
  // console.log(req.body);
  // console.log(req.params);
  // console.log(req.query);
  // console.log(!!JSON.stringify(req.body.pwd));

  if (!!JSON.stringify(req.query.status)) {
    // console.log('状态');
    //修改状态
    let strSql = "UPDATE employee set emp_status = ? where emp_id = ?"
    let result = await sqlQuery(strSql, [req.query.status, req.params.id])
    res.json(1)
  } else if (!!JSON.stringify(req.query.pwd)) {
    // console.log('密码');
    //修改密码
    let strSql = "UPDATE employee set emp_pwd = ? where emp_id = ?"
    let result = await sqlQuery(strSql, [md5(req.query.pwd), req.params.id])
    res.json(1)
  } else {
    // console.log("信息");
    let { emp_role, emp_gender, emp_tel, emp_email } = req.query
    let strSql = "UPDATE employee set emp_role=?, emp_gender=?, emp_tel=?, emp_email=? where emp_id = ?"
    // console.log([emp_role, emp_gender, emp_tel, emp_email, req.params.id]);
    let result = await sqlQuery(strSql, [emp_role, emp_gender, emp_tel, emp_email, req.params.id * 1])
    res.json(1)
  }
})

//查询具体员工信息
app.get("/staff/:id", async (req, res) => {
  let strSql = "select * from employee where emp_id = ?"
  let result = await sqlQuery(strSql, [req.params.id])
  // console.log(result);
  res.json(result)
})



//展示顾客信息
app.get('/message/customer', async (req, res) => {
  let { query, pagenum } = req.query
  if (query == '') {
    let strSql = "select COUNT(*) as total from customer"
    let totalpage = await sqlQuery(strSql)
    strSql = "select * from customer limit ?,5"
    let customers = await sqlQuery(strSql, [(pagenum - 1) * 5])
    res.json({
      totalpage, customers
    })
  } else {
    let strSql = "select COUNT(*) as total from customer where tel like '%" + query + "%'"
    let totalpage = await sqlQuery(strSql)
    strSql = "select * from customer where tel like '%" + query + "%' limit ?,5"
    let customers = await sqlQuery(strSql, [(pagenum - 1) * 5])
    res.json({
      totalpage, customers
    })
  }
})


//修改顾客是否被禁用
app.put("/customer/:id", async (req, res) => {
  //修改状态
  // console.log(req.body);
  // console.log(req.params.id);
  let strSql = "UPDATE customer set isDelete = ? where id = ?"
  let result = await sqlQuery(strSql, [req.body.status, req.params.id])
  res.json(1)
})


// 展示演出计划列表
app.get("/message/schedule", async (req, res) => {
  let { pagenum } = req.query
  // console.log(query,pagenum);
  let strSql = "select COUNT(*) as total from schedule where isDelete = 0"
  let totalpage = await sqlQuery(strSql)
  strSql = "select s.schedule_day, s.schedule_time, s.price, s.schedule_id schedule_id,  m.id movieid, m.title movie, sc.id screenid, sc.name studio  from (select * from schedule where isDelete = 0 limit ?,5) s LEFT JOIN movie m ON s.movie_id = m.id LEFT JOIN screen sc ON s.studio_id = sc.id"
  let schedules = await sqlQuery(strSql, [(pagenum - 1) * 5])
  // console.log(schedules);
  res.json({
    totalpage, schedules
  })

})

//删除演出计划
app.delete('/schedule/:id', async (req, res) => {
  // let strSql = "delete from schedule where schedule_id = ?"
  let strSql = "update schedule set isDelete = 1 where schedule_id = ?"
  let result = await sqlQuery(strSql, [req.params.id])
  res.json(1)
})

//显示演出计划的电影名和影厅名
// app.get('/schedule/ms',async (req,res) => {
//   // console.log(req.query.movieid);
//   let strSql = "select title from movie where id = ?"
//   let result1 = await sqlQuery(strSql, [req.query.movieid * 1])
//   // console.log(result1[0].title);
//   strSql = "select name from screen where id = ?"
//   let result2 = await sqlQuery(strSql, [req.query.studioid * 1])
//   // console.log(result2[0].name);
//   res.json({
//     movie:result1[0].title,
//     studio:result2[0].name,
//     item:req.query.item
//   })
// })

// app.get('/schedule/m/:id',async(req,res) => {
//   let strSql = "select title from movie where id = ?"
//   let result = await sqlQuery(strSql, [req.params.id * 1])
//   // console.log(result[0].title);
//   res.json(result[0].title)
// })



//获取电影列表
app.get("/movies", async (req, res) => {
  let strSql = "select id,title value from movie"
  let result = await sqlQuery(strSql)
  // console.log(result);
  res.json(result)
})

//获取演出厅列表
app.get("/studios", async (req, res) => {
  let strSql = "select id,name value from screen"
  let result = await sqlQuery(strSql)
  // console.log(result);
  res.json(result)
})

//添加演出计划
app.post("/message/schedule", async (req, res) => {

  // console.log(req.body);

  let { mValue, sValue, dValue, tValue, price, timestamp } = req.body
  // console.log(dValue,tValue);
  let strSql
  strSql = "select id from movie where title = ?"
  let movieid = await sqlQuery(strSql, [mValue])
  // console.log(movieid[0].id);
  strSql = "select id from screen where name = ?"
  let studioid = await sqlQuery(strSql, [sValue])

  //判断当前演出厅有没有矛盾的放映计划
  strSql = "select max(timestamp) as time from schedule where isDelete = 0 and studio_id = ?"
  let tamp = await sqlQuery(strSql, [studioid[0].id])
  // console.log(tamp[0].time);
  tamp = Number(tamp[0].time) + 10800000

  if (Number(timestamp) > tamp) {
    // console.log(studioid[0].id);
    strSql = "insert into schedule (studio_id,movie_id,schedule_day,schedule_time,price,timestamp,isDelete) values (?,?,?,?,?,?,?)"
    let result = await sqlQuery(strSql, [studioid[0].id, movieid[0].id, dValue, tValue, price, timestamp, 0])

    // 根据演出计划和放映厅添加票的信息
    //先获取演出计划id
    strSql = "select schedule_id as id from schedule where studio_id = ? AND movie_id = ? AND schedule_day = ? AND schedule_time = ? AND price = ? AND timestamp = ?"
    let scheduleid = await sqlQuery(strSql, [studioid[0].id, movieid[0].id, dValue, tValue, price, timestamp])

    //再新增座位票情况
    strSql = "select set_state as state from seat where studio_id = ?"
    let condition = await sqlQuery(strSql, [studioid[0].id])

    strSql = "insert into ticket (schedule_id,conditions) values (?,?)"
    result = await sqlQuery(strSql, [scheduleid[0].id, condition[0].state])
    res.json(1)
  }
  else{
    res.json(0)
  }

})




//用户

//用户注册
app.post("/cregister", async (req, res) => {
  // console.log(req.body);
  let { ruser, rtel, rpwd } = req.body
  rpwd = md5(rpwd)
  let strSql = "select * from customer where tel = ?"
  let constt = await sqlQuery(strSql, [rtel])
  if (constt.length != 0) {
    res.json(0)
  } else {
    let strSql = "insert into customer (user,tel,pwd,isDelete) values (?,?,?,?)"
    let result = await sqlQuery(strSql, [ruser, rtel, rpwd, 0])
    res.json(1)
  }
})

//用户登录
app.get("/clogin", async (req, res) => {
  // console.log(req.query);
  let { ltel, lpwd } = req.query
  lpwd = md5(lpwd)
  let strSql = "select * from customer where tel = ?"
  let constt = await sqlQuery(strSql, [ltel])
  if (constt.length == 0) {
    res.json({ state: 0 })
  } else {
    let strSql = "select pwd,isDelete from customer where tel = ?"
    let result = await sqlQuery(strSql, [ltel])
    if (result[0].isDelete == '1') {
      res.json({ state: 2 })
    } else {
      if (result[0].pwd == lpwd) {
        res.json({
          state: 1,
          tel: ltel
        })
      } else {
        res.json({ state: -1 })
      }
      // console.log(result);
    }
  }
})

//index页面获取十个电影数据
app.get("/index", async (req, res) => {
  let strSql
  strSql = "select COUNT(*) as total from movie"
  let totalpage = await sqlQuery(strSql)
  strSql = "select * from movie limit 0,10"
  let movies = await sqlQuery(strSql)
  res.json({
    totalpage,
    movies,
  })
})

//smovie页面获取所有电影信息
app.get("/smovie", async (req, res) => {
  let strSql
  strSql = "select * from movie"
  let movies = await sqlQuery(strSql)
  res.json(movies)
})

//详情页面获取电影信息
app.get('/mdetail/:id', async (req, res) => {
  // console.log(req.params.id);
  let strSql = "select * from movie where id = ?"
  let movie = await sqlQuery(strSql, [req.params.id])
  res.json(movie[0])
})

//详情页根据id和时间获得放映演出计划
app.get('/sdetail/:id', async (req, res) => {
  // console.log(req.params.id);
  // console.log(req.query.time);
  let strSql = "select s.schedule_id id,s.schedule_time time, m.filmlen length, m.language,  sc.name studio ,s.price from (select * from schedule where schedule_day = ? and movie_id = ? and isDelete = 0 ) s LEFT JOIN movie m ON s.movie_id = m.id LEFT JOIN screen sc ON s.studio_id = sc.id"
  let schedules = await sqlQuery(strSql, [req.query.time, req.params.id])
  res.json(schedules)
})


//购票页面展示座位信息
app.get("/seats", async (req, res) => {
  // console.log(req.query);
  let { scheduleid } = req.query
  let strSql = "select conditions from ticket where schedule_id = ?"
  let result = await sqlQuery(strSql, [scheduleid])
  // console.log(result[0].conditions);
  res.json(result[0].conditions)
})

//购票页面获取电影信息
app.get("/Tschedule", async (req, res) => {
  let { scheduleid } = req.query
  // console.log(movieid,scheduleid);
  let strSql = "select m.cover,s.schedule_day, s.schedule_time, s.price, m.title movie,sc.`name` studio, m.filmlen length ,m.type,m.`language` from (select * from schedule where schedule_id = ?) s LEFT JOIN movie m ON s.movie_id = m.id LEFT JOIN screen sc ON s.studio_id = sc.id"
  let result = await sqlQuery(strSql, [scheduleid])
  // console.log(result[0]);
  res.json(result[0])
})

//确认支付页面获取电影信息
app.get("/Oschedule", async (req, res) => {
  let { scheduleid } = req.query
  let strSql = "select s.schedule_day, s.schedule_time,s.price, m.title movie,sc.`name` studio from (select * from schedule where schedule_id = ?) s LEFT JOIN movie m ON s.movie_id = m.id LEFT JOIN screen sc ON s.studio_id = sc.id"
  let result = await sqlQuery(strSql, [scheduleid])
  // console.log(result[0]);
  res.json(result[0])
})

//加锁
app.get("/locking", async (req, res) => {
  // console.log(req.query);
  let { tickets, scheduleid, tel, time, count, pretime } = req.query

  //查询顾客id
  let strSql = "select id from customer where tel = ?"
  let customerid = await sqlQuery(strSql, [tel])

  //看是否重复  重复则不加进数据库里
  strSql = "select order_id,order_status from torder where customer_id = ? AND schedule_id = ? AND seat = ? "
  let order1 = await sqlQuery(strSql, [customerid[0].id, scheduleid, tickets])
  if (order1.length != 0 && order1[0].order_status == '-2') {
    // console.log("重复");
    res.json({ orderid: order1[0].order_id, customerid: customerid[0].id })
    return
  }
  //同一个人更换座位
  strSql = "select order_id,order_status from torder where customer_id = ? AND schedule_id = ?"
  let order2 = await sqlQuery(strSql, [customerid[0].id, scheduleid])
  if (order2.length != 0 && order2[0].order_status == '-2') {
    // console.log("更改");
    strSql = "UPDATE torder set seat = ? , order_prepay_time = ? where order_id = ?"
    let result = await sqlQuery(strSql, [tickets, pretime, order2[0].order_id])
    res.json({ orderid: order2[0].order_id, customerid: customerid[0].id })
    return
  }
  //查询演出计划时间戳  价格
  strSql = "select timestamp,price from schedule where schedule_id = ?"
  let schedule = await sqlQuery(strSql, [scheduleid])
  // console.log(schedule[0].price);
  let totalprice = schedule[0].price * count
  //增加订单表信息
  strSql = "insert into torder (customer_id,schedule_id,seat,order_prepay_time,order_exist_time,order_price,order_status) values (?,?,?,?,?,?,?)"
  let result = await sqlQuery(strSql, [customerid[0].id, scheduleid, tickets, pretime, schedule[0].timestamp, totalprice, '-2'])

  strSql = "select order_id from torder where order_prepay_time = ?"
  result = await sqlQuery(strSql, [pretime])
  res.json({ orderid: result[0].order_id, customerid: customerid[0].id })
})

app.put('/payoff', async (req, res) => {
  let { scheduleid, orderid, customerid, paytime, tickets } = req.body
  //查询ticket表 更改座位情况
  tickets = JSON.parse(tickets)
  // console.log(customerid);
  let strSql = "select conditions from ticket where schedule_id = ?"
  let seat = await sqlQuery(strSql, [scheduleid])
  seat = JSON.parse(seat[0].conditions)
  // console.log(JSON.parse(seat[0].conditions)[0]);
  for (let i = 0; i < tickets.length;) {
    // console.log(tickets[i],tickets[i+1]);
    // console.log(seat[tickets[i]][tickets[i + 1]]);
    seat[tickets[i]][tickets[i + 1]] = customerid
    i = i + 2
  }

  seat = JSON.stringify(seat)
  strSql = "UPDATE ticket set conditions = ? where schedule_id = ?"
  let result = await sqlQuery(strSql, [seat, scheduleid])

  //更改订单情况
  strSql = "UPDATE torder set order_pay_time = ? , order_status = ? where order_id = ?"
  result = await sqlQuery(strSql, [paytime, '1', orderid])
  res.json(1)
})

//我的订单页面的信息获取
app.get("/porder", async (req, res) => {
  let { tel, status } = req.query
  //查询顾客id
  let strSql = "select id from customer where tel = ?"
  let customerid = await sqlQuery(strSql, [tel])

  //查询
  strSql = `SELECT sch.schedule_day, sch.schedule_time,m.cover, m.title movie, sc.name studio,o.order_id,o.schedule_id,o.seat,o.order_pay_time,o.order_price,o.order_status 
  FROM (select order_id,schedule_id,seat,order_pay_time,order_price,order_status 
  from torder 
  where customer_id = ? and order_status = ?) o
  LEFT JOIN schedule sch
    ON o.schedule_id = sch.schedule_id
  LEFT JOIN movie m
    ON sch.movie_id = m.id
  LEFT JOIN screen sc 
    ON sch.studio_id = sc.id
  `
  let info = await sqlQuery(strSql, [customerid[0].id, status])

  // console.log(info);
  res.json(info)
})



//上传图片
app.post("/posts", multer({
  //设置文件存储路径
  dest: '../ttms/public/img'
}).array('file', 1), function (req, res, next) {
  // console.log(req);
  let files = req.files;
  let file = files[0];
  let fileInfo = {};
  let path = '../ttms/public/img/' + Date.now().toString() + '_' + file.originalname;
  fs.renameSync('../ttms/public/img/' + file.filename, path);
  //获取文件基本信息
  fileInfo.type = file.mimetype;
  fileInfo.name = file.originalname;
  fileInfo.size = file.size;
  fileInfo.path = path;
  res.json({
    code: 0,
    msg: 'OK',
    data: fileInfo
  })
})

app.post("/post", multer({
  //设置文件存储路径
  dest: '../ttms/public/img'
}).array('file', 1), function (req, res, next) {
  console.log(req);
  let file = req.query.file;
  let fileInfo = {};
  console.log(file.originalname);
  let path = '../ttms/public/img/' + Date.now().toString() + '_' + file.originalname;
  fs.renameSync('../ttms/public/img/' + file.filename, path);
  //获取文件基本信息
  fileInfo.type = file.mimetype;
  fileInfo.name = file.originalname;
  fileInfo.size = file.size;
  fileInfo.path = path;
  res.json({
    code: 0,
    msg: 'OK',
    data: fileInfo
  })
})

app.get("/disposts", (req, res) => {
  // console.log(req.query.filepath);
  fs.unlink(req.query.filepath, function (err) {
    if (err) throw err;
  })
})

//倒计时
app.get("/countdown", async (req, res) => {
  // console.log(req.query.id);
  let strSql = "select order_prepay_time from torder where order_id = ?"
  let pretime = await sqlQuery(strSql, [req.query.id])
  res.json(pretime[0].order_prepay_time)
})

//删除无效订单
app.delete('/delorder/:id', async (req, res) => {
  let strSql = "delete from torder where order_id = ?"
  let result = await sqlQuery(strSql, [req.params.id])
  res.json(1)
})

//退票
app.put("/retorder", async (req, res) => {
  let { id, seats } = req.body
  // console.log(seats);
  //更改票的信息
  let strSql = "UPDATE torder set order_status = ? where order_id = ?"
  let result = await sqlQuery(strSql, ['-1', id])

  //更改座位表信息
  strSql = "SELECT conditions from ticket where schedule_id = (select schedule_id from torder where order_id = ?)"
  let seat = await sqlQuery(strSql, [id])
  seat = JSON.parse(seat[0].conditions)
  for (let i = 0; i < seats.length; i++) {
    seat[seats[i][0]][seats[i][1]] = 0
  }
  seat = JSON.stringify(seat)
  strSql = "UPDATE ticket set conditions = ? where schedule_id = (select schedule_id from torder where order_id = ?)"
  result = await sqlQuery(strSql, [seat, id])


  res.json(1)
})


//一键删除过期的演出计划
app.put('/message/overdue', async (req, res) => {
  //一键删除过期的演出计划  更改删除isDelete字段
  // console.log(req.query)
  let strSql = "update schedule set isDelete = 1 where timestamp <= ?"
  let resule = await sqlQuery(strSql, [req.query.time])
  res.json(1)
})

// 更改顾客订单的状态
app.put("/changeState", async (req, res) => {
  let strSql = "update torder t LEFT JOIN schedule s ON t.schedule_id = s.schedule_id set order_status = 0 where t.order_status = 1 and s.`timestamp` <= ?"
  let resule = await sqlQuery(strSql, [req.query.time])
  res.json(1)
})


app.listen(5500, () => {
  console.log("server is start")
})